#include "FileLog.h"
#include <time.h>

FileLog::FileLog(void)
{
	entryID = 0;
	fileTime = 0;
	files2Keep = 48; // constant for now - keeps 1 day worth of log
	seconds2Keep = 60*60*30; // keep for 30 minutes each

}

FileLog::~FileLog(void)
{
}

void FileLog::NewId()
{
	entryID++;
}

void FileLog::SetMinLogLevel(LOGLEVEL MinLogLevel)
{
	minLogLevel = MinLogLevel;
}

string FileLog::GetFileLogName()
{
	time_t now = time(NULL);
	bool header = false;
	if((now - fileTime) > seconds2Keep)
	{
		fileTime = now;
		header = true;
	}
	struct tm *ts;
	ts = localtime(&fileTime);

	char buf[40];
	int size = sizeof(buf);

	strftime(buf, size, "%Y-%m-%d-%H-%M-%S", ts);
	string file = logFolder + filename;
	file.append((char*)&buf);
	file += ".LOG";
	if(header)
	{
		fs.open(file.c_str(), ios::app);
		fs << "Time" << "\t" << "Id" << "\t" << "Method" << "\t" << "IP" << "\t" <<
			"Level" << "\t" << "Message" << "\t" << "Request"
			<< "\t" << "Body" << std::endl;
		fs.close();

	}
	return file;
}

// Write Log Entry
void FileLog::WriteLog(LOGLEVEL LogLevel, const string& Method, const string& IP, const string& Body, const string& Request, const string& Message)
{
	// No log, just return
	if(minLogLevel == None)
	{
		return;
	}
	// Entry is not supposed to be entered, just return.
	if((int)LogLevel > (int)minLogLevel)
	{
		return;
	}
	time_t now = time(NULL);
	
	struct tm *ts;
	ts = localtime(&now);
	char buf[40];
	int size = sizeof(buf);
	strftime(buf, size, "%Y-%m-%d %H:%M:%S", ts);

	fs.open(GetFileLogName().c_str(), ios::app);
	fs << buf << "\t" << entryID << "\t" << Method << "\t" << IP << "\t" << levelStrings[LogLevel] << "\t" << Message << "\t" << Request
		<< "\t" << Body << std::endl;
	fs.close();
	
}

void FileLog::SetFolder(const string& Folder)
{
	logFolder = Folder;
	// Append \ if not in the folder name.
	if(logFolder.substr(logFolder.length()-1, 1) != "\\")
	{
		logFolder += "\\";
	}

}

// Enter file base name (e.g. "mylog")
void FileLog::SetFileBaseName(const string& FileBaseName)
{
	filename = FileBaseName;
}
